package ptij.ADSL.de.ATUC;

import ptolemy.kernel.*;
import ptolemy.kernel.util.*;
import ptolemy.data.*;
import ptolemy.data.expr.*;
import ptolemy.data.type.*;
import ptolemy.actor.*;

import ptij.ADSL.common.MuxDataFrame;

//////////////////////////////////////////////////////////////////////////
//// MuxSyncRx
/**

@author Ivan Jeukens
*/
public class MuxSyncRx extends TypedAtomicActor {        
    
    public MuxSyncRx(CompositeEntity container, String name) throws
            NameDuplicationException, IllegalActionException {
        super(container, name);
    
        input = new TypedIOPort(this, "input", true, false);
	input.setTypeEquals(BaseType.OBJECT);
		
	LS0 = new TypedIOPort(this, "LS0", false, true);
	LS0.setTypeEquals(BaseType.OBJECT);

	S = new Parameter(this, "S", new IntToken(1));		
    }

    ///////////////////////////////////////////////////////////////////
    ////                     ports and parameters                  ////
    
    public TypedIOPort input;   
    public TypedIOPort LS0;

    public Parameter S;    

    ///////////////////////////////////////////////////////////////////
    ////                         public methods                    ////    
    
     public void attributeChanged(Attribute attribute)
            throws IllegalActionException {
        if(attribute == S) {
 	    IntToken it = (IntToken) S.getToken();
	    _S = it.intValue();           
        }
	else {
            super.attributeChanged(attribute);
        }            
    }

    public void initialize() throws IllegalActionException {
        super.initialize();
	_frameCounter = 0;
    }
    
    public void fire() throws IllegalActionException {
	_receiveData();	
    }

    ///////////////////////////////////////////////////////////////////
    ////                         private methods                   ////

    private void _receiveData() throws IllegalActionException {
        ObjectToken ot = (ObjectToken) input.get(0);
	MuxDataFrame mf = (MuxDataFrame) ot.getValue();

	if(_frameCounter == 0) {
//	    System.out.println("$$ ATUC $$ Received FAST Frame");
//	    mf.print();
	}
	else {
//	    System.out.println("$$ ATUC $$ Received Interleaved Frame");
//	    mf.print();
	}
//	System.out.print("\n");
        _frameCounter = (_frameCounter + 1) % (_S + 1);

	int [] data = mf.getLS0();
	if(data.length != 0) {
	    LS0.send(0, new ObjectToken(data));
	}
    }

    ///////////////////////////////////////////////////////////////////
    ////                         private variables                 ////
         
    private int _frameCounter;
    private int _S;
}
